import UIKit

class TabViewController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTabs()
        setupTabBarAppearance()
        
        // 监听主题变化
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }
    
    private func setupTabs() {
        // 创建首页
        let mainVC = MainViewController()
        let mainNav = UINavigationController(rootViewController: mainVC)
        mainNav.tabBarItem = UITabBarItem(
            title: "扫描",
            image: UIImage(systemName: "doc.text.viewfinder"),
            selectedImage: UIImage(systemName: "doc.text.viewfinder.fill")
        )
        
        // 创建设置页面
        let settingsVC = SettingsViewController()
        let settingsNav = UINavigationController(rootViewController: settingsVC)
        settingsNav.tabBarItem = UITabBarItem(
            title: "我的",
            image: UIImage(systemName: "gearshape"),
            selectedImage: UIImage(systemName: "gearshape.fill")
        )
        
        // 设置视图控制器数组
        viewControllers = [mainNav, settingsNav]
        
        // 设置默认选中的标签
        selectedIndex = 0
    }
    
    private func setupTabBarAppearance() {
        updateTabBarAppearance()
    }
    
    private func updateTabBarAppearance() {
        let isDark = ThemeManager.shared.isDarkMode
        
        // 设置标签栏外观
        tabBar.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        tabBar.tintColor = isDark ? .white : .black
        tabBar.unselectedItemTintColor = ThemeManager.Colors.tabBarUnselectedColor(for: isDark)
        
        // 设置标签栏样式
        if #available(iOS 15.0, *) {
            let appearance = UITabBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
            
            // 设置选中和未选中状态的颜色
            appearance.stackedLayoutAppearance.selected.iconColor = isDark ? .white : .black
            appearance.stackedLayoutAppearance.selected.titleTextAttributes = [
                .foregroundColor: isDark ? UIColor.white : UIColor.black
            ]
            
            appearance.stackedLayoutAppearance.normal.iconColor = ThemeManager.Colors.tabBarUnselectedColor(for: isDark)
            appearance.stackedLayoutAppearance.normal.titleTextAttributes = [
                .foregroundColor: ThemeManager.Colors.tabBarUnselectedColor(for: isDark)
            ]
            
            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = appearance
        }
    }
    
    @objc private func themeDidChange() {
        updateTabBarAppearance()
        setNeedsStatusBarAppearanceUpdate()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return ThemeManager.shared.isDarkMode ? .lightContent : .darkContent
    }
} 
